﻿namespace com.oakwoodsys.ConsultantCare
{
    using System.Collections.Generic;
    using System.Reflection;
    using com.oakwoodsys.SharePoint;

    using Microsoft.SharePoint;
    using com.oakwoodsys.Extensions.SharePointExtensions;
    using ReferenceDao = ConsultantCareDao.DeletionDao;

    public class Deletion_Definition_WebLevel : CustomBaseDefinition
    {
        #region Constructors

        public Deletion_Definition_WebLevel( SPFeatureReceiverProperties properties )
            : base( properties )
        {
        }

        ~Deletion_Definition_WebLevel( )
        {
            Dispose( false );
        }

        #endregion Constructors

        #region Methods

        public override void Create( )
        {
            base.Create( );
            CreateList( getListDefn( ) );
            addEventReceiver( );
        }

        public override void Delete( )
        {
            base.Delete( );
            DeleteList( getListDefn( ), true );
        }

        ListDefn getListDefn( )
        {
            return new ListDefn
            {
                RootFolderName = ReferenceDao.ListName,
                Title = "Consultant Care Background Deletion Support",
                Description = "List for background deletions.",
                Hidden = true
            };
        }

        void addEventReceiver( )
        {
            string assembly = Assembly.GetAssembly( typeof( DeletionItemEventReceiver ) ).FullName;
            string className = typeof( DeletionItemEventReceiver ).FullName;

            using ( SPWeb spWeb = Properties.GetWeb( ) )
            {
                SPList spList = spWeb.Lists.GetListByRootFolder( ReferenceDao.ListName );

                List<SPEventReceiverDefinition> l = new List<SPEventReceiverDefinition>( );
                foreach ( SPEventReceiverDefinition v in spList.EventReceivers )
                    if ( ( v.Type == SPEventReceiverType.ItemAdded ) &&
                        v.Assembly.Equals( assembly ) && v.Class.Equals( className ) )
                        l.Add( v );
                for ( int i = l.Count - 1; i >= 0; i-- )
                    l[ i ].Delete( );

                spList.EventReceivers.Add( SPEventReceiverType.ItemAdded, assembly, className );
            }
        }

        #endregion Methods
    }
}